<template>
    <div class='EditKey'>
        <div v-if="select_key == ''" class="kong">{{ text }}</div>
        <div v-else class="box">
            <div class="head" :class="{'xiao':xiao}">
                <div class="item left">
                    <div class="operate" v-show="!xiao">
                        <el-button @click="refresh" :loading="loading" size="mini" type="info" icon="el-icon-refresh-right"></el-button>
                        <el-button @click="delete_key" :loading="loading" size="mini" type="danger" icon="el-icon-delete"></el-button>
                    </div>
                    <div class="key">
                        <el-input class="input" v-model="data.key" size="mini" :disabled="loading">
                            <template #prepend>
                                <el-tooltip effect="dark" :content="'key类型为：'+typeList3[data.type]" placement="top">
                                    <el-button :loading="loading" style="padding-left:6px;padding-right:6px;" type="text">{{typeList2[data.type]}}</el-button>
                                </el-tooltip>
                            </template>
                            <template #append v-if="data.key != dataTemp.key">
                                <el-button :loading="loading" @click="save_key(false)" style="padding-left:6px;padding-right:6px;">提交</el-button>
                            </template>
                        </el-input>
                    </div>
                </div>

                <div class="item right">
                    <div class="operate" v-show="xiao">
                        <el-button @click="refresh" :loading="loading" size="mini" type="info" icon="el-icon-refresh-right"></el-button>
                        <el-button @click="delete_key" :loading="loading" size="mini" type="danger" icon="el-icon-delete"></el-button>
                    </div>
                    <div class="ttl">
                        <el-input class="input" v-model="data.ttl" size="mini" :disabled="loading">
                            <template #prepend>
                                <el-tooltip effect="dark" content="过期时间,留空可设置为永久" placement="top">
                                    <el-button style="padding-left:6px;padding-right:6px;" type="text">ttl</el-button>
                                </el-tooltip>
                            </template>
                            <template #append v-if="data.ttl != dataTemp.ttl">
                                <el-button :loading="loadingSave_ttl" type="success" @click="save_ttl" style="padding-left:6px;padding-right:6px;">{{data.ttl == '' ? '设置永久':'提交'}}</el-button>
                            </template>
                        </el-input>
                        <span style="margin-left: 8px;">秒</span>
                    </div>
                </div>

            </div>
            <div class="contest">
                <edit-str v-if="key_type == 'string'"></edit-str>
                <edit-list v-if="key_type == 'list'"></edit-list>
                <edit-set v-if="key_type == 'set'"></edit-set>
                <edit-hash v-if="key_type == 'hash'"></edit-hash>
                <edit-zset v-if="key_type == 'zset'"></edit-zset>
            </div>
        </div>
    </div>
</template>

<script>
import { p_error } from '@/utils/prompt';
import EditList from './EditList/index';
import EditSet from './EditSet/index';
import EditHash from './EditHash/index';
import EditStr from './EditStr/index';
import EditZset from './EditZset/index';
import { defineComponent, reactive, toRefs } from 'vue';
import { mapGetters } from 'vuex'
import { getKey, delKey } from '@/api/key';
import { pub_rename, pub_expire, pub_persist } from '@/api/key/pub';
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'
export default defineComponent({
    name: 'EditKey',
    components: { EditList, EditSet, EditHash, EditStr, EditZset },
    setup(omprops, content) {
        const typeList2 = {
            ing: "",
            none: "none",
            string: "String",
            hash: "Hash",
            list: "List",
            set: "Set",
            zset: "Zset",
        }
        const typeList3 = {
            ing: "",
            none: "none(当前key已不存在)",
            string: "String(字符串)",
            hash: "Hash(哈希)",
            list: "List(列表)",
            set: "Set(集合)",
            zset: "Zset(有序集合)",
        }
        const state = reactive({
            text: '<--请先在左侧选择要查看的key',
            typeList2,
            typeList3,
            loading: false,
            data: {
                key: "key",
                type: "String",
                ttl: "0",
            },
            dataTemp: {
                key: "",
                type: "String",
                ttl: "0"
            },
            loadingSave_ttl: false,
        })
        return toRefs(state)
    },
    props: [],  // 选中的key
    computed: {
        ...mapGetters([
            'bw',
            'select_key',
            'key_type'
        ]),
        xiao() {
            return this.bw < 861
        },
    },
    watch: {
        select_key(newKey, oldKey) {
            if (newKey != '') {
                this.refresh()
            }
        }
    },
    methods: {
        // 刷新
        refresh() {
            this.$store.commit('key/SET_TYPE', 'ing')
            this.loading = true
            this.dataTemp.key = this.select_key
            this.data.key = this.select_key
            this.data.type = 'ing'
            this.data.ttl = '0'
            getKey(this.select_key).then((res) => {
                this.$store.commit('key/SET_TYPE', res.data.type)
                this.data.type = res.data.type
                this.data.key = res.data.key
                this.data.ttl = res.data.ttl
                this.dataTemp = JSON.parse(JSON.stringify(this.data))
            }).catch((e) => {
                if (e.code == 4041) {
                    this.data.type = 'none'
                }
            }).finally(() => {
                this.loading = false
            })
        },
        // 删除
        delete_key() {
            p_error(`确定要删除 ${this.select_key} 吗？这将不可以恢复`, (instance, done) => {
                instance.confirmButtonLoading = true
                delKey(this.select_key).then((res) => {
                    ElNotification({
                        title: '删除成功',
                        message: `${res.data.key} 已被成功删除`,
                        type: 'success',
                    })
                    this.$store.commit('key/SET_SELECT', '')
                    this.$emit('delKey', res.data.key)
                    done()
                }).finally(() => {
                    instance.confirmButtonLoading = false
                })
            })
        },

        save_ttl() {
            this.loadingSave_ttl = true;
            // 通知
            const Notif = (s) => { ElNotification({ title: '成功', message: s, type: 'success', }) }
            // 改变ttl
            const gaibian = (key, ttl) => {
                if (this.select_key == key) {
                    this.dataTemp.ttl = ttl
                    this.data.ttl = ttl
                }
            }
            // 关闭正在加载
            const fin = () => { this.loadingSave_ttl = false; }
            if (this.data.ttl == '') {
                // 设置永久
                pub_persist(this.select_key).then((res) => {
                    gaibian(res.data.map.key, '-1')
                    Notif(`${this.select_key} 已成功设置为永久`)
                }).finally(fin)
            } else {
                pub_expire(this.select_key, this.data.ttl).then((res) => {
                    gaibian(res.data.map.key, res.data.map.ttl)
                    Notif(`${this.select_key} 已成功设置 ${res.data.map.ttl} 秒后过期`)
                }).finally(fin)
            }
        },

        // 保存key
        save_key(cover) {
            this.loading = true
            pub_rename(this.dataTemp.key, this.data.key, cover).then((res) => {
                this.dataTemp.key = res.data.map.newKey
                this.data.key = res.data.map.newKey
                ElNotification({
                    title: '修改成功',
                    message: `${res.data.map.oldKey} -> ${res.data.map.newKey}`,
                    type: 'success',
                })
                this.$store.commit('key/SET_SELECT', res.data.map.newKey)
                this.$emit('editKey', {
                    oldKey: res.data.map.oldKey,
                    newKey: res.data.map.newKey
                })
            }).catch((res) => {
                if (res.code == 4101) {
                    ElMessageBox.confirm(
                        `${res.data.map.key} 已存在,类型为:${res.data.map.type},是否继续更新key, 这将覆盖`,
                        'key已存在',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'danger',
                        }
                    ).then(() => {
                        this.save_key(true)
                    })
                }
            }).finally(() => {
                this.loading = false
            })
        },
    },
})
</script>

<style scoped lang="less">
.EditKey {
    width: 100%;
    height: 100%;
    display: flex;
    padding-left: 20px;
    align-items: center;
    flex-direction: column;

    .box {
        height: 100%;
        // max-width: 700px;
        width: 100%;
        display: flex;
        flex-direction: column;
        .head {
            width: 100%;
            max-width: 741px;
            display: flex;
            flex-direction: row;
            // 操作按钮
            .operate {
                display: flex;
                flex-direction: row;
            }
            .item {
                // margin-top: 6px;
                display: flex;
                flex-direction: row;
                align-items: center;
                &.left {
                    flex: 2.5;
                    .key {
                        margin-left: 10px;
                        width: 100%;
                    }
                }
                // 右边的box 包含小的时候的按钮，和ttl
                &.right {
                    flex: 1;
                    .ttl {
                        max-width: 260px;
                        min-width: 150px;
                        margin-left: 10px;
                        display: flex;
                        flex-direction: row;
                        align-items: center;
                    }
                }
                .input {
                    flex: 1;
                }
            }

            // 小
            &.xiao {
                flex-direction: column;
                .item {
                    &.left {
                        .key {
                            margin-left: 0;
                        }
                    }
                    &.right {
                        // 宽带小的时候，换行了，要距顶部一点距离
                        margin-top: 6px;
                        .ttl {
                            max-width: 100%;
                            flex: 1;
                        }
                    }
                }
            }
        }
        .contest {
            flex: 1;
            position: relative;
            overflow-y: hidden;
            position: relative;
        }
        max-height: 100%;
    }

    .kong {
        height: 100%;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 15px;
    }
}
</style>